package com.plugin.sproutcore.util;

import java.io.File;

/**
 * Useful methods for working with files.
 * 
 * @author Michael Pugliese
 * 
 */
public class FileUtil 
{
	/**
	 * Find files starting from a folder and working up. This can be expensive.
	 * 
	 * @param name
	 * Return the file that matches this name.
	 * @param source
	 * The folder to search in. Must be a directory.
	 * 
	 * @return
	 * Return the found match. Returns null if nothing is matched to the name.
	 */
	public static File findFileRecursivly(final String name, 
			final File source)
	{
		if (source != null)
		{
			if (source.getName().equals(name)) {
				return source;
			}
			if (source.isDirectory())
			{
				final File[] fileList = source.listFiles();
				for (File file:fileList)
				{
					file = findFileRecursivly(name, file);
					if (file != null) {
						return file;
					}
				}
			}
		}
		return null;
	}
	
	/**
	 * Find a file or folder within a given source folder.
	 * 
	 * @param name
	 * Return the file that matches this name.
	 * @param source
	 * The folder to search in. Must be a directory.
	 * 
	 * @return
	 * Return the found match. Returns null if nothing is matched to the name.
	 */
	public static File findFile(final String name, final File source)
	{
		if (source != null && source.exists() && source.isDirectory())
		{
			final File[] fileList = source.listFiles();
			for (File file:fileList)
			{
				if (file.getName().equals(name))
				{
					return file;
				}
			}
		}
		return null;
	}
}
